import pymongo
import datetime
import random
import yaml
import os
import sys
import requests
import json


client = pymongo.MongoClient("localhost", 27017)
updb = client['anjiudate']
getdb = client['dateanjiu']


filepath = os.path.abspath(sys.argv[0])
files = os.path.join(os.path.dirname(filepath),"setting.yml")
ret = open(files,"r",encoding="utf-8")
yamlread= ret.read()
ret.close()

daytod = datetime.datetime.today()
liuc = yaml.load(yamlread, Loader=yaml.FullLoader)


game_dict = {}
game_update = {}


for x in liuc["gamelist"]:
    if x["name"]:
        game_dict.update({x["name"]:x["price"]})



def getsum(db,time,su,game=None):
    if game:
        times = db.find({"time":time,"game":game})
    else:
        times = db.find({"time":time})
    gamedict = {}
    for gm in times:
        if gm['model'] == "新增":
            if not game:
                if gm['game'] not in game_dict:
                    gamedict.update({gm['game'] + "+" + gm['chennl'] + "+" + gm['model']:0})
            else:
                gamedict.update({gm['game'] + "+" + gm['chennl'] + "+" + gm['model']:0})
    print("留存比例:",str(int(su*100))+"%","时间:",time,"影响游戏:",gamedict)
    for game in gamedict:
        games = db.find({"game":game.split("+")[0],"chennl":game.split("+")[1],"time":time})
        list_ = []
        for i in games:
            list_.append(i)
        sum = int(len(list_)*su)
        se = 0
        while sum>se:
            s = random.randint(0,len(list_)-1)
            list_[s].pop("_id")
            getdb['data'].insert_one(list_[s])
            list_.remove(list_[s])
            se += 1
        update_dict(game.split("+")[0],se)


def update_dict(n,s):
    if n in game_update:
        game_update.update({n:game_update[n] + s})
    else:
        game_update.update({n:s})


def sendmessage(message):
    url = "https://oapi.dingtalk.com/robot/send?access_token=8f37512a3ca08ff43cec93ac52d828eaa48c9c9871ec9c43116611fd1f17d61d"
    HEADERS = {
        "Content-Type": "application/json ;charset=utf-8"
    }
    message = message
    String_textMsg = {
        "msgtype": "text",
        "text": {"content": message},
        "at": {
            "atMobiles": [
                "15296518791"
            ],
            "isAtAll": 1
        }
    }
    String_textMsg = json.dumps(String_textMsg)
    res = requests.post(url, data=String_textMsg, headers=HEADERS)
    return res.text


def mongouplc():
    if liuc["clear"] == True:
        getdb['data'].delete_many({})
    for uscor in updb.list_collection_names():
        day = daytod - datetime.datetime.strptime(uscor,"%Y-%m-%d")
        if day.days < int(liuc["time"])*2-10:
            se = 0
            for i in liuc["languagdb"]:
                getsum(updb[uscor],str(datetime.datetime.now()+datetime.timedelta(-se))[:10],i)
                se += 1
            for y in game_dict:
                se = 0
                for z in liuc[game_dict[y]]:
                    getsum(updb[uscor],str(datetime.datetime.now()+datetime.timedelta(-se))[:10],z,game=y)
                    se += 1
    if liuc['dink'] == True:
        str_ = str(datetime.date.today()) + " [留存播报通知]\n"
        for i in game_update:
            str_ += "留存游戏:" + i + " - " + str(game_update[i]) + "\n"
        sendmessage(str_)


if __name__ == "__main__":
    mongouplc()
